package com.umfwechat.lightprogram.controller.my;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.lightprogram.vo.SetAgentRateCfg;
import com.umfwechat.util.PropertyUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.common.RetCode;
import com.umpay.sp.model.saas.RatesConf;
import com.umpay.sp.service.saas.remote.RatesServiceRemote;

/**
 * 获取费率信息
 * @author xuhuibing
 *
 */

@Controller
@RequestMapping("/Rates")
public class RatesController {
	private static Logger logger = LoggerFactory.getLogger(RatesController.class);
	
	@Resource
	private RatesServiceRemote ratesServiceRemote;
	
	/**
	 * 查询费率信息
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryRates")
	@ResponseBody
	public JSONObject getRatesByAgentId(HttpServletRequest request, HttpServletResponse response) throws Exception{		
		JSONObject json= new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG, "查询费率成功");
		String reqJSON = (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param = null;
		try {
			param = JSONObject.fromObject(reqJSON);
		} catch (Exception e1) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "请求参数不足");
			logger.info("【请求数据转换异常】");
		}
		String agentId = param.optString(CommonConsts.LOGINAGENTID);
		//组装请求参数
		ReqMessage req = ReqMessageUtil.makeSpReq();
		//设置请求参数
		req.put(CommonConsts.AGENTID,agentId);//agentId
		logger.info("【请求查询费率接口:】查询费率 请求参数:" + agentId);
		ResMessage res=null;
		try {
			logger.info("【请求查询费率 】查询费率 入参为:" + req );
			res = ratesServiceRemote.getRatesByAgentId(req);
			logger.info("【请求查询费率 】查询费率 出参为:" +res);
		} catch(Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "查询异常，请稍后重试");
			logger.info("【调用查询费率信息接口失败】" );
			return json;
		}
		//判断返回码是否为0000
		String retCode = res.getRetCode();
		if(RetCode.SUCCESS.equals(retCode)){
			 RatesConf ratesConf = (RatesConf) res.getResMap().get("ratesConf");
			 if(ratesConf==null){
				 json.put(CommonConsts.RETCODE, "0001");
				 json.put(CommonConsts.RETMSG, "暂时未添加费率");
				 return json;
			 }
			 String highRate = ratesConf.getHighRate();
			 String lowRate = ratesConf.getLowRate();
			 json.put(CommonConsts.HIGHRATE, highRate);
			 json.put(CommonConsts.LOWRATE, lowRate);//lowRate
		}else{
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "查询费率信息失败");
			logger.info("【查询费率信息失败】");
			return json;
		}
		return json;
	}
	
	/**
	 * 保存代理商立码付费率
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/saveRates")
	@ResponseBody
	public JSONObject saveRates(HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject json= new JSONObject();
		//收集客户端请求数据
		String reqJSON = (String) request.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param = null;
		try {
			param = JSONObject.fromObject(reqJSON);
		} catch (Exception e1) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "请求参数不足");
			logger.info("【请求保存费率信息转换异常】");
		}
		String agentId = param.optString(CommonConsts.LOGINAGENTID);//loginAgentId 代理商编号
		String highRate = param.optString(CommonConsts.HIGHRATE);//highRate 最高费率
		String lowRate = param.optString(CommonConsts.LOWRATE);//lowRate 最低费率
		double svHigh = Double.valueOf(highRate)*1000;// 输入的最高费率
		double svlowRate = Double.valueOf(lowRate)*1000;//输入的最低费率
			
		//----------------------------------查询多级代理商关系-------------------------------------
	
		//组装请求信息
		Map<String,Object> validatParam = new HashMap<String,Object>();//创建对象,保存请求信息
		com.umfwechat.common.ReqMessage reqMessage2 = ReqMessageUtil.makeReq();
		validatParam.put(CommonConsts.RPID, reqMessage2.getRpid());
		validatParam.put(CommonConsts.AGENTID, agentId);
		validatParam.put("relType", "4");//0或不传-查询完整级别关系,1-查询直接下级,2-查询所有下级,3-查询直接上级,4-查询所有上级
		Map<String,Object> crmResult = null;
		try {
			logger.info("【查询多级代理商关系】输入参数:" + validatParam);
			XStream xstream = new XStream(new DomDriver());
//			String url="http://10.10.77.76:7000/restUserManager/rest2/QueryAgentRel/QueryAgentRel.xml";
			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgentRel");
			crmResult = (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, validatParam);
			logger.info("【查询多级代理商关系】输出参数:" + crmResult);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "调用crm查询多级代理商关系接口异常");
			logger.info("【调用crm查询多级代理商关系接口异常】");
		}
		String retCodeRel = (String) crmResult.get("retCode");
		if(!RetCode.SUCCESS.equals(retCodeRel)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "调用crm查询多级代理商关系接口失败");
			logger.info("【调用crm查询多级代理商关系接口失败】");
			return json;
		}
		
		Map<String, Object> agentMetaMap = (Map<String, Object>) crmResult.get("agentMetaMap");
		List<String> maxAgentIds = (List<String>) agentMetaMap.get("agent[1]List");//获取最高级别代理商
		String maxAgentId = (String) maxAgentIds.get(0);//最高级别代理商编号
		String relAgentId = null;
		Integer minAgentId = Integer.valueOf(agentMetaMap.get("minLevel").toString())-1;
		List<String> relAgentIds = (List<String>) agentMetaMap.get("agent["+minAgentId+"]List");//获取直属上级
		//如果不等于空,证明是二三级: 1,查询上级代理上费率区间,2,用顶级再查低价 
		if(relAgentIds!= null){
			relAgentId = (String) relAgentIds.get(0);//获取直属上级代理商编号
			
			
		//-----------------------------------查询上级代理商费率区间---------------------------------------------------
			
			com.umpay.sp.model.common.ReqMessage reqMapRates = ReqMessageUtil.makeSpReq();
			reqMapRates.put("agentId",relAgentId);
			logger.info("请求费率参数：" + agentId);
			com.umpay.sp.model.common.ResMessage resMessRates=null;
			try {
				logger.info("【请求查询费率的出参】输出参数：" + reqMapRates);
				resMessRates = ratesServiceRemote.getRatesByAgentId(reqMapRates);
				logger.info("【请求查询费率的出参】输出参数：" + resMessRates);
			} catch (Exception e) {
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG, "查询异常，请稍后重试！");
				logger.info("【查询费率信息失败】");
				return json;
			}
			String retCodeRates = resMessRates.getRetCode();
			if(!RetCode.SUCCESS.equals(retCodeRates)){
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG, "查询上级代理商费率失败");
				logger.info("【查询上级代理上费率信息失败】");
				return json;
			}
			RatesConf ratesConfRel = (RatesConf) resMessRates.getResMap().get("ratesConf");
			if(ratesConfRel == null){
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG, "查询上级代理商费率为空");
				logger.info("【查询上级代理商费率为空】");
				return json;
			}
			//上级代理商区间,是判断区间范围,不判断最低费率是否高于低价
			double highRateRel = Double.valueOf(ratesConfRel.getHighRate())*1000;//上级代理商最高费率
			double LowRateRel = Double.valueOf(ratesConfRel.getLowRate())*1000;//上级代理商最低费率
			
			//保存的费率-->联动最低价-上级代理商区间->10%==准备就绪
			if(svlowRate < LowRateRel || svlowRate > highRateRel ||svlowRate > 10000){
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG,"设置的最低费率必须在"+LowRateRel/1000+"到"+highRateRel/1000+"范围内");
				return json;
			}
			if(svHigh > highRateRel || svHigh < LowRateRel || svHigh>10000){
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG,"设置的最高费率必须在"+LowRateRel/1000+"到"+highRateRel/1000+"范围内");
				return json;
			}
		}
		//------------------------------查询联动为代理商设置的低价费率---------------------------------

		
			com.umfwechat.common.ReqMessage reqMessage = ReqMessageUtil.makeReq();
			Map<String, Object> reqMap = reqMessage.getReqMap();
			reqMap.put(CommonConsts.RPID, reqMessage.getRpid());
			reqMap.put(CommonConsts.REQDATE, reqMessage.getReqDate());
			reqMap.put(CommonConsts.REQTIME, reqMessage.getReqTime());
			reqMap.put(CommonConsts.AGENTID, maxAgentId);//最大级别代理商编号,一级
			String agentProfitType = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","agentProfitType");
			reqMap.put("type", agentProfitType);//定价产品 type就传 10，传0时有数据方便测试
			Map<String,Object> frontResult = null;
			try {
				String agentProfitUrl=PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","agentProfitUrl");
				logger.info("【设置代理商最低价URl为:】" + agentProfitUrl);
				logger.info(" 【调用联动给代理商设置的最低价】输入参数: " + reqMap);
				frontResult = com.umpay.http.platform2.HttpUtil.httpPostForm2Xml
						(agentProfitUrl, reqMap);
				logger.info(" 【调用联动给代理商设置的最低价】返回参数: " + frontResult);
			} catch (Exception e) {
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG, "调用联动设置立码付费率异常");
				logger.info("【调用联动设置立码付费率异常】");
				return json;
			}
			String retCode4 = (String) frontResult.get("retCode");
			if(!RetCode.SUCCESS.equals(retCode4)){
				json.put("retCode", "0001");
				json.put("retMsg","调用费率查询接口失败");
				return json;
			}
			String listString = (String) frontResult.get("list");
			double lowRateStander=200d;
			if(listString!=null){
				//TODO 格式转换成json
				JSONArray jArray = JSONArray.fromObject(listString);
				List<SetAgentRateCfg> list = jArray.toList(jArray,SetAgentRateCfg.class);
				logger.info("【代理商设置的费率list为:】"+list.toString());
				//循环查询低价list
				for(SetAgentRateCfg sa: list){
					String sDate = sa.getStartDate();//获取生效时间
					String eDate = sa.getEndDate();//获取截止时间
					//TODO new () API
					DateFormat df = new SimpleDateFormat("yyyyMMdd");
					long startDate = df.parse(sDate).getTime();//开始有效时间
					long endDate = df.parse(eDate).getTime();//结束有效时间
					long nowDate = new Date().getTime();//现在时间
					logger.info("有效时间" + startDate + "有效结束时间:" + endDate + "现在时间:" + nowDate);
					if(startDate<=nowDate && nowDate<=endDate){
						if("25".equals(sa.getRuleValue())){
							double fratVal=Double.parseDouble((sa.getFratVal()));
							lowRateStander = fratVal*100000;	//"fratVal": "0.001234"
						}
					}
				}
			}
//			logger.info("调用联动给代理商设置的费率接口得到最低费率为："+lowRateStander/100000);
			//如果该代理商是一级代理商,只查询联动给的低价,最低费率大于等于低价费率
			if(svlowRate < lowRateStander || svHigh > 10000){
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG,"设置的最低费率低于代理商底价或高于10%");
				return json;
			}

			
		// ---------------------------------保存立码付费率--------------------------------------------------
		
		//组装dubbo方服务参数
		com.umpay.sp.model.common.ReqMessage req = ReqMessageUtil.makeSpReq();
		req.put(CommonConsts.AGENTID,agentId);
		com.umpay.sp.model.common.ResMessage resSel=null;
		try {
			logger.info("【请求查询费率参数】查询费率 入参: " + agentId);
			resSel = ratesServiceRemote.getRatesByAgentId(req);
			logger.info("【请求查询费率】查询费率 返回参: " + resSel);
		} catch (Exception e) {
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "查询异常，请稍后重试");
			logger.info("【调用查询费率接口失败】");
			return json;
		}
		String retCode = resSel.getRetCode();
		if(!RetCode.SUCCESS.equals(retCode)){
			json.put(CommonConsts.RETCODE, "0001");
			json.put(CommonConsts.RETMSG, "【获取费率信息失败】");
			logger.info("【获取费率信息失败】");
			return json;
		}
		RatesConf ratesConf = (RatesConf) resSel.getResMap().get("ratesConf");
		if(ratesConf != null){
			com.umpay.sp.model.common.ReqMessage updateReq = ReqMessageUtil.makeSpReq();
			updateReq.put(CommonConsts.AGENTID, agentId);
			updateReq.put(CommonConsts.HIGHRATE, highRate);
			updateReq.put(CommonConsts.LOWRATE, lowRate);
			com.umpay.sp.model.common.ResMessage resUpde=null;
			try {
				logger.info("【更新立马付费率】 请求参数: " + updateReq);
				resUpde = ratesServiceRemote.updateRates(updateReq);
				logger.info("【更新立马付费率】 返回参数: " + resUpde);
			} catch (Exception e) {
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG, "调用更新费率接口异常");
				logger.info("【调用费率修改接口异常】");
				return json;
			}
			String retCode1 = resUpde.getRetCode();
			if(!RetCode.SUCCESS.equals(retCode1)){
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG, "更新立码付费率接口异常");
				logger.info("【更新立码付费率接口异常】");
				return json;
			}
			
			json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
			json.put(CommonConsts.RETMSG, "更新立码付费率接口成功");
			logger.info("【更新立码付费率接口成功】");
			return json;
		}else{
			com.umpay.sp.model.common.ReqMessage saveReq = ReqMessageUtil.makeSpReq();
			saveReq.put(CommonConsts.AGENTID, agentId);
			saveReq.put(CommonConsts.HIGHRATE, highRate);
			saveReq.put(CommonConsts.LOWRATE, lowRate);
			com.umpay.sp.model.common.ResMessage resSave=null;
			try {
				logger.info("【请求保存费率接口信】请求保存费率 入参:" + saveReq);
				resSave = ratesServiceRemote.saveRates(saveReq);
				logger.info("【请求保存费率接口信】请求保存费率 返回参:" + resSave);
			} catch (Exception e) {
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG, "调用保存费率接口异常");
				logger.info("【调用保存费率接口异常】");
				return json;
			}
			String retCode3 = resSave.getRetCode();
			if(!RetCode.SUCCESS.equals(retCode3)){
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG, "保存立码付费率接口异常");
				logger.info("【保存立码付费率接口异常】");
				return json;
			}
			
			json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
			json.put(CommonConsts.RETMSG,"保存费率信息成功");
			return json;
		}
	}
}





